/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package kimo.bl;

import DsrvMain.persistence.entities.T001User;
import captions.CaptionsEnum;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import Dsrv6.bl.Dsrv6Person;
import DsrvMain.bl.DsrvMainPerson;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import static kimo.bl.zkUtils.*;
import kimo.persistence.controllers.AdtTypeJpaController;
import kimo.persistence.controllers.DaokJpaController;
import kimo.persistence.controllers.PrefectureJpaController;
import kimo.persistence.controllers.ProducerJpaController;
import kimo.persistence.controllers.ProductCategoryJpaController;
import kimo.persistence.controllers.ProductJpaController;
import kimo.persistence.controllers.ProductTypeJpaController;
import kimo.persistence.controllers.ProductionJpaController;
import kimo.persistence.controllers.RawProductJpaController;
import kimo.persistence.controllers.RawProductTypeJpaController;
import kimo.persistence.controllers.RegionJpaController;
import kimo.persistence.controllers.SexJpaController;
import kimo.persistence.controllers.UnitLocationTypeJpaController;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.entities.AdtType;
import kimo.persistence.entities.Daok;
import kimo.persistence.entities.Municipality;
import kimo.persistence.entities.Prefecture;
import kimo.persistence.entities.Producer;
import kimo.persistence.entities.Product;
import kimo.persistence.entities.ProductCategory;
import kimo.persistence.entities.ProductType;
import kimo.persistence.entities.Production;
import kimo.persistence.entities.RawProduct;
import kimo.persistence.entities.RawProductType;
import kimo.persistence.entities.Region;
import kimo.persistence.entities.Sex;
import kimo.persistence.entities.UnitLocationType;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.zkoss.util.media.AMedia;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Div;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Messagebox.ClickEvent;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;

/**
 *
 * @author a381u296
 */
public class ProducerBL1 extends SelectorComposer<Component> {

    @Wire
    private Div d0;

    @Wire
    private Textbox maae_afm;
    @Wire
    private Grid g1;
    @Wire
    private Textbox producer_afm;
    @Wire
    private Textbox producer_surname;
    @Wire
    private Textbox producer_first_name;
    @Wire
    private Textbox producer_father_name;
    @Wire
    private Datebox producer_birthdate;
    @Wire
    private Listbox producer_sex_id;
    @Wire
    private Listbox producer_adtType_id;
    @Wire
    private Textbox producer_adt;
    @Wire
    private Datebox producer_adt_issue_date;
    @Wire
    private Textbox producer_adt_issue_department;
    @Wire
    private Textbox producer_phone;
    @Wire
    private Textbox producer_mobile_phone;
    @Wire
    private Textbox producer_fax;
    @Wire
    private Textbox producer_email;

    @Wire
    private Button g1next;

    @Wire
    private Grid g2;
    @Wire
    private Listbox producer_region_id;
    @Wire
    private Listbox producer_prefecture_id;
    @Wire
    private Listbox producer_municipality_id;
    @Wire
    private Textbox producer_address_street;
    @Wire
    private Textbox producer_address_number;
    @Wire
    private Intbox producer_address_zip;

    @Wire
    private Grid g3;
    @Wire
    private Checkbox producer_rural_same;
    @Wire
    private Listbox producer_rural_region_id;
    @Wire
    private Listbox producer_rural_prefecture_id;
    @Wire
    private Listbox producer_rural_municipality_id;
    @Wire
    private Textbox producer_rural_address_street;
    @Wire
    private Textbox producer_rural_address_number;
    @Wire
    private Textbox producer_rural_address_zip;

    @Wire
    private Grid g4;
    @Wire
    private Radiogroup unitLocation;
    @Wire
    private Listbox producer_daok_cd;

    @Wire
    private Grid g5;
    @Wire
    private Textbox production_farm_osde;
    @Wire
    private Doublebox production_farm_area;
    @Wire
    private Listbox production_raw_product_type_id;
    @Wire
    private Listbox production_raw_product_id;
    @Wire
    private Doublebox production_raw_product_kilos;
    @Wire
    private Listbox production_product_category_id;
    @Wire
    private Listbox production_product_type_id;
    @Wire
    private Combobox production_product_id;
    @Wire
    private Doublebox production_product_kilos;

    @Wire
    private Listbox production;

    @Wire
    private Div g6;
    @Wire
    private Label msgDateLbl;

    private EntityManagerFactory emf;
    private ProducerJpaController producerJpaController;
    private SexJpaController sjc;
    private AdtTypeJpaController atjc;
    private RegionJpaController rjc;
    private PrefectureJpaController pfjc;
    private DaokJpaController djc;
    private ProductCategoryJpaController pcjc;
    private ProductTypeJpaController ptjc;
    private UnitLocationTypeJpaController ultjc;

    private RawProductTypeJpaController rawProductTypeJpaController;

    private ProductCategoryJpaController productCategoryJpaController;

    private List<Sex> sexs;
    private List<AdtType> adts;
    private List<Region> regions;
    private List<Daok> daoks;
    private List<Municipality> emptyMunicipalitys;
    private List<UnitLocationType> ults;
    private List<RawProductType> rawProductTypes;
    private List<ProductCategory> productCategorys;

    private Producer producerToSave;

    private boolean new_producer;

    private static final String captionsFileName = "captions.captions";
    private static final ResourceBundle rb = ResourceBundle.getBundle(captionsFileName);
    private String username;
    private String T001email;

    //private List<ProductCategory> 
    private void bindControllers() {
        emf = Persistence.createEntityManagerFactory("DSrvKimoPU");
        producerJpaController = new ProducerJpaController(emf);
        sjc = new SexJpaController(emf);
        atjc = new AdtTypeJpaController(emf);
        rjc = new RegionJpaController(emf);
        pfjc = new PrefectureJpaController(emf);
        djc = new DaokJpaController(emf);
        pcjc = new ProductCategoryJpaController(emf);
        ptjc = new ProductTypeJpaController(emf);
        ultjc = new UnitLocationTypeJpaController(emf);

        //g5
        rawProductTypeJpaController = new RawProductTypeJpaController(emf);
        productCategoryJpaController = new ProductCategoryJpaController(emf);

    }

    private void createLists() {
        sexs = sjc.findSexEntities();
        adts = atjc.findAdtTypeEntities();
        regions = rjc.findRegionEntities();
        daoks = djc.findDaokEntities();
        // μια αδεια λιστα για να μην σκαει το σκασμενο
        emptyMunicipalitys = new ArrayList();
        ults = ultjc.findUnitLocationTypeEntities();

        productCategorys = productCategoryJpaController
                .findProductCategoryEntities();
        rawProductTypes = rawProductTypeJpaController
                .findRawProductTypeEntities();

    }

    private void setModels() {
        // θα γεμισω μονον τα μοντελα των αρχικων combo
        // τα υπολοιπα αφου εξαρτωνται απο επιλογες θα τα φτιαχνω μετα

        producer_sex_id.setModel(new ListModelList<Sex>(sexs));
        producer_adtType_id.setModel(new ListModelList<AdtType>(adts));
        producer_region_id.setModel(new ListModelList<Region>(regions));
        producer_daok_cd.setModel(new ListModelList<Daok>(daoks));

        producer_municipality_id.setModel(new ListModelList<Municipality>(emptyMunicipalitys));
        producer_rural_region_id.setModel(new ListModelList<Region>(regions));

        unitLocation.setModel(new ListModelList<UnitLocationType>(ults));

        production_product_category_id
                .setModel(new ListModelList<ProductCategory>(productCategorys));

        production_raw_product_type_id.setModel(new ListModelList<RawProductType>(rawProductTypes));

        production.setModel(new ListModelList<Production>());

    }

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);

        // εφαγα μια ωρα να καταλαβω οτι αυτο παιζει ΜΟΝΟ στο doaftercompose
        username = Executions.getCurrent().getParameter("u");

        bindControllers();
        createLists();
        setModels();

        if (username != null) {
            //Messagebox.show(username);
            DsrvMainPerson dmp = new DsrvMainPerson();
            T001User findUsername = dmp.findUsername(username);

            T001email = findUsername.getEmail();
            fakeLogin(findUsername.getTaxCode());

        }

        //@todo : να το αφαιρεσω καθως ελενχω για null
        //producerToSave = new Producer();
    }

    // Listeners για τα buttons μετακινησης
    @Listen("onClick = #g1next")
    public void g1next() {
        // τα get value πετανε wrong value exception αν η τιμη δεν ειναι
        // συμφωνη με το contstraint και ετσι ουσιαστικα ΑΚΥΡΩΝΕΙ την ενεργεια

        // και μετεφερα τον ελεχγο στο getfromUIg1
        getfromUIg1(producerToSave);
        g1.setVisible(false);
        g2.setVisible(true);
        updateUIg2(producerToSave);
    }

    @Listen("onClick = #g2prev")
    public void onG2Prev() {
        g1.setVisible(true);
        g2.setVisible(false);
    }

    @Listen("onClick = #g2next")
    public void g2next() {
        getfromUIg2(producerToSave);
        g2.setVisible(false);
        g3.setVisible(true);
        updateUIg3(producerToSave);
    }

    @Listen("onClick = g3prev")
    public void onG3Prev() {

    }

    @Listen("onClick = #g3next")
    public void g3next() {
        getfromUIg3(producerToSave);
        g3.setVisible(false);
        g4.setVisible(true);
        updateUIg4(producerToSave);
    }

    @Listen("onClick = #g4next")
    public void g4next() {

        getfromUIg4(producerToSave);
        saveProducer();
        g4.setVisible(false);
        g5.setVisible(true);
        updateUIg5(producerToSave);
    }

    private Producer kimoSearchAFM(String afm) {
        Producer producer;
        try {
            producer = (Producer) producerJpaController.getEntityManager()
                    .createNamedQuery("Producer.findByProducerAfm")
                    .setParameter("producerAfm", afm)
                    .getSingleResult();

        } catch (Exception e) {
            producer = null;
        }
        return producer;
    }

    public void fakeLogin(String afmtofind) {

        producerToSave = kimoSearchAFM(afmtofind);
        if (producerToSave != null) { // ΝΑΙ, ΥΠΑΡΧΕΙ ΣΤΟ ΚΙΜΟ

            if (producerToSave.getProducerSubmittedAppliation() == false) { // ΕΧΟΥΜΕ ΜΙΣΗ ΑΙΤΗΣΗ
                new_producer = false;
                myMessagebox(CaptionsEnum.AFM_NOT_COMPLETED_APPLICATION);
                d0.setVisible(false);

                updateUIg1(producerToSave);
            } else { // ΕΧΟΥΜΕ ΟΛΟΚΛΗΡΩΜΕΝΗ ΑΙΤΗΣΗ
                myMessagebox(CaptionsEnum.AFM_COMPLETED_APPLICATION);
                d0.setVisible(false);
                g6.setVisible(true);
            }
        } else { // ΟΧΙ, ΔΕΝ ΥΠΑΡΧΕΙ ΣΤΟ ΚΙΜΟ - ΨΑΧΝΟΥΜΕ ΣΤΟ ΜΑΑΕ
            Dsrv6Person mp = new Dsrv6Person(afmtofind);
            producerToSave = null;
            producerToSave = mp.FindAFM();
            if (producerToSave != null) { // ΤΟΝ ΒΡΗΚΑΜΕ (ΚΑΙ ΕΙΝΑΙ ΑΓΡΟΤΗΣ)
                d0.setVisible(false);
                new_producer = true;

                producerToSave.setProducerEmail(T001email);

                myMessagebox(mp.getMessage());
                updateUIg1(producerToSave);
            } else { // ΔΕΝ ΒΡΕΘΗΚΕ ΚΑΘΟΛΟΥ Ή ΔΕΝ ΕΙΝΑΙ ΑΓΡΟΤΗΣ
                myMessagebox(mp.getMessage());
            }
        }
    }

    @Listen("onSelect = #producer_sex_id")
    public void onSelectProducerSexId() {
        Clients.clearWrongValue(producer_sex_id);

    }

    @Listen("onSelect = #producer_region_id")
    public void regionSelect() {
        ListModel<Region> r = producer_region_id.getModel();
        Region pregion = r.getElementAt(producer_region_id.getSelectedIndex());
        Region findRegion = rjc.findRegion(pregion.getRegionId());
        List<Prefecture> ps = findRegion.getPrefectureList();
        producer_prefecture_id.setModel(new ListModelList<Prefecture>(ps));
        producer_municipality_id.setModel(new ListModelList<Municipality>(emptyMunicipalitys));
        producer_municipality_id.clearSelection();
        // producer_municipality_id.setModel(null);
    }

    @Listen("onSelect = #producer_prefecture_id")
    public void prefectureSelect() {
        ListModel<Prefecture> p = producer_prefecture_id.getModel();
        Prefecture prefecture = p.getElementAt(producer_prefecture_id.getSelectedIndex());
        Prefecture findPrefecture = pfjc.findPrefecture(prefecture.getPrefectureId());
        List<Municipality> ml = findPrefecture.getMunicipalityList();
        producer_municipality_id.setModel(new ListModelList<Municipality>(ml));
    }

    @Listen("onSelect = #producer_rural_region_id")
    public void ruralRegionSelect() {
        ListModel<Region> r = producer_rural_region_id.getModel();
        Region pregion = r.getElementAt(producer_rural_region_id.getSelectedIndex());
        Region findRegion = rjc.findRegion(pregion.getRegionId());
        List<Prefecture> ps = findRegion.getPrefectureList();
        producer_rural_prefecture_id.setModel(new ListModelList<Prefecture>(ps));
        producer_rural_municipality_id.setModel(new ListModelList<Municipality>(emptyMunicipalitys));
        producer_rural_municipality_id.clearSelection();
    }

    @Listen("onSelect = #producer_rural_prefecture_id")
    public void ruralPrefectureSelect() {
        ListModel<Prefecture> p = producer_rural_prefecture_id.getModel();
        Prefecture prefecture = p.getElementAt(producer_rural_prefecture_id
                .getSelectedIndex());
        Prefecture findPrefecture = pfjc.findPrefecture(prefecture.getPrefectureId());
        List<Municipality> ml = findPrefecture.getMunicipalityList();
        producer_rural_municipality_id.setModel(new ListModelList<Municipality>(ml));
    }

    @Listen("onSelect = #production_raw_product_type_id")
    public void rawProductTypeSelect() {
//        Set<ProductType> productTypes = ((ListModelList) 
//                  production_product_type_id.getModel()).getSelection();
//
//        List<Product> products = productTypes.iterator().next().getProductList();
//
//        production_product_id.setModel(new ListModelList<Product>(products));

        Set<RawProductType> rpts = ((ListModelList) production_raw_product_type_id.getModel()).getSelection();

        List<RawProduct> rawProducts = rpts.iterator().next().getRawProductList();

        production_raw_product_id.setModel(new ListModelList<RawProduct>(rawProducts));

    }

    @Listen("onSelect = #production_product_category_id")
    public void productCategoryIdSelect() {
        ListModel<ProductCategory> r = production_product_category_id.getModel();
        ProductCategory productCategory = r.getElementAt(production_product_category_id.getSelectedIndex());
        ProductCategory findProductCategory = productCategoryJpaController.
                findProductCategory(productCategory.getProductCategoryId());
        List<ProductType> productTypes = findProductCategory.getProductTypeList();

        production_product_type_id.setModel(new ListModelList<ProductType>(productTypes));

        //production_product_id.setModel(new ListModelList<Product>());
    }

    @Listen("onSelect = #production_product_type_id")
    public void productTypeIdSelect() {

        Set<ProductType> productTypes = ((ListModelList) production_product_type_id.getModel()).getSelection();

        List<Product> products = productTypes.iterator().next().getProductList();

        production_product_id.setModel(new ListModelList<Product>(products));

    }

    @Listen("onClick = #add_production")
    public void addProduction() {

        // αρχιζουμε να δημιουργουμε το ενα production item
        Production productionItem = new Production();
        //pr.setProductionProducerId(p);

        productionItem.setProductionFarmOsde(production_farm_osde.getValue());
        productionItem.setProductionFarmArea(production_farm_area.getValue());

        Set<RawProductType> rpts = ((ListModelList) production_raw_product_type_id
                .getModel()).getSelection();

        if (rpts.isEmpty()) {
            throw new WrongValueException(production_raw_product_type_id,
                    rb.getString(CaptionsEnum.SELECT_GENERIC.toString()));
        }

        Set<RawProduct> rp = ((ListModelList) production_raw_product_id
                .getModel()).getSelection();
        if (rp.isEmpty()) {
            throw new WrongValueException(production_raw_product_id,
                    rb.getString(CaptionsEnum.SELECT_GENERIC.toString()));
        }

        // παιρνουμε τα πρωτογενους κιλα
        productionItem.setProductionRawProductKilos(production_raw_product_kilos.getValue());

        Set<ProductCategory> pcs = ((ListModelList) production_product_category_id
                .getModel()).getSelection();
        if (pcs.isEmpty()) {
            throw new WrongValueException(production_product_category_id,
                    rb.getString(CaptionsEnum.SELECT_GENERIC.toString()));
        }

        Set<ProductType> productTypes = ((ListModelList) production_product_type_id
                .getModel()).getSelection();
        if (productTypes.isEmpty()) {
            throw new WrongValueException(production_product_type_id,
                    rb.getString(CaptionsEnum.SELECT_GENERIC.toString()));
        }

        // για το raw product
        // θελω controler 
        RawProductJpaController rawProductJpaController = new RawProductJpaController(emf);
        // παιρνω το selection απο το listbox
        // XXX : Εδω το getmodel σκαει (NPE) καθως αν δεν εχει κανει επιλογη σε
        // ομαδα (type) 

        Set<RawProduct> rps = ((ListModelList) production_raw_product_id.getModel()).getSelection();

        if (!rps.isEmpty()) { // αν ΔΕΝ ειναι αδειο - κατι διαλεξε
            // βρισκω το id του (ΑΠΟ ΤΗΝ ΒΑΣΗ ? ΓΙΑΤΙ ? Δεν θα επαιζε απο το listmodel ?)
            RawProduct rawProduct = rawProductJpaController.findRawProduct(rps.iterator().next().getRawProductId());
            productionItem.setProductionRawProductId(rawProduct);
        } else { // πετα ενα exception αμα δεν εχει διαλεξει κατι
            throw new WrongValueException(production_raw_product_id,
                    rb.getString(CaptionsEnum.SELECT_RAW.toString()));
        }

        // για το product 
        Product product;
        // θελω controler
        ProductJpaController productJpaController = new ProductJpaController(emf);
        // παιρνω το selection απο το COMBO box 
        Set<Product> ps = ((ListModelList) production_product_id.getModel()).getSelection();

        if (ps.isEmpty()) { // δεν εχει διαλεξει κατι
            if (!production_product_id.getValue().isEmpty()) { // κατι εχει γραψει ομως
                // αρα φτιαξε ενα νεο product 
                product = new Product();
                // βαλε του ονομα
                product.setProductName(production_product_id.getValue());
                // το οποιο πρεπει να ανηκει σε ενα product_type
                // αρα παιρνω το selection του production type
                Set<ProductType> pts
                        = ((ListModelList) production_product_type_id.getModel()).getSelection();

                if (!pts.isEmpty()) { // αν δεν ειναι αδειο
                    // παρε το πρωτο item και βαλε το σαν product type στο product
                    ProductType productType = pts.iterator().next();
                    product.setProductTypeId(productType);
                    productionItem.setProductionProductId(product);
                    // και ενημερωσε και το combo ?
                    ((ListModelList) production_product_type_id.getModel()).add(product);
                    // βαλε το και στην βαση ?
                    productJpaController.create(product);
                } else { // αλλιως μυνηματακι για επιλογη product type
                    throw new WrongValueException(production_product_type_id,
                            rb.getString(CaptionsEnum.SELECT_PRODUCT_TYPE.toString()));
                }
            }
        } else { // εχει κανει μια επιλογη 
            // για να εχει κανει επιλογη εχει διαλεξει product_type
            // αρα παρε το product και βαλε το στο production item
            product = ps.iterator().next();

            productionItem.setProductionProductId(product);
        }

        // βαλε και τα κιλα του product
        productionItem.setProductionProductKilos(production_product_kilos.getValue());

        productionItem.setProductionYear(new Date());

        // και προσθεσε το στην λιστα
        productionItem.setProductionProducerId(producerToSave);

        producerToSave.getProductionList().add(productionItem);

        production.setModel(new ListModelList<Production>(producerToSave.getProductionList()));

        ProductionJpaController pjc = new ProductionJpaController(emf);
        pjc.create(productionItem);

        clearUI5();
    }

    private void clearUI5() {

// TODO: ΝΑ καθαρισω ολα 
        production_farm_osde.setRawValue("");
        production_farm_area.setRawValue("");

        production_raw_product_type_id.clearSelection();
        // not supported operation -- αρα αναγκαστικα θα καθαρισω ολο το ListModel
        // ((ListModelList) production_raw_product_id.getModel()).getSelection.clear

        ((ListModelList) production_raw_product_type_id.getModel()).clear();
        production_raw_product_type_id.setModel((new ListModelList<RawProductType>(rawProductTypes)));

        ((ListModelList) production_raw_product_id.getModel()).clear();

        production_raw_product_kilos.setRawValue("");

        ((ListModelList) production_product_category_id.getModel()).clear();
        production_product_category_id.setModel(
                (new ListModelList<ProductCategory>(productCategorys)));

        ((ListModelList) production_product_type_id.getModel()).clear();
        ((ListModelList) production_product_id.getModel()).clear();

        production_product_id.setRawValue("");

        production_product_kilos.setRawValue("");

    }

    @Listen("onDelete = #production")
    public void removeProduction(ForwardEvent evt
    ) {

        Button btn = (Button) evt.getOrigin().getTarget();
        Listitem litem = (Listitem) btn.getParent().getParent();

        Production prod = (Production) litem.getValue();

        //((ListModelList) production.getModel()).remove(prod) ;
        producerToSave.getProductionList().remove(prod);
        production.setModel(new ListModelList<Production>(producerToSave.getProductionList()));

        ProductionJpaController pjc = new ProductionJpaController(emf);
        try {
            pjc.destroy(prod.getProductionId());
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(ProducerBL1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Listen("onCheck = #producer_rural_same")
    public void sameRuralAddress() {
        if (producer_rural_same.isChecked()) {

            ((ListModelList) producer_rural_region_id.getModel())
                    .setSelection(((ListModelList) producer_region_id
                            .getModel()).getSelection());

            producer_rural_prefecture_id.setModel(producer_prefecture_id.getModel());

            ((ListModelList) producer_rural_prefecture_id.getModel())
                    .setSelection(((ListModelList) producer_prefecture_id
                            .getModel()).getSelection());

            producer_rural_municipality_id.setModel(producer_municipality_id.getModel());

            ((ListModelList) producer_rural_municipality_id.getModel())
                    .setSelection(((ListModelList) producer_municipality_id
                            .getModel()).getSelection());

            producer_rural_address_street.setValue(producer_address_street.getValue());
            producer_rural_address_number.setValue(producer_address_number.getValue());
            producer_rural_address_zip.setValue(producer_address_zip.getRawText());
            producer_rural_region_id.setDisabled(true);
            producer_rural_prefecture_id.setDisabled(true);
            producer_rural_municipality_id.setDisabled(true);
            producer_rural_address_street.setDisabled(true);
            producer_rural_address_number.setDisabled(true);
            producer_rural_address_number.setDisabled(true);
            producer_rural_address_zip.setDisabled(true);
        } else {
            producer_rural_region_id.setDisabled(false);
            producer_rural_prefecture_id.setDisabled(false);
            producer_rural_municipality_id.setDisabled(false);
            producer_rural_address_street.setDisabled(false);
            producer_rural_address_number.setDisabled(false);
            producer_rural_address_number.setDisabled(false);
            producer_rural_address_zip.setDisabled(false);
        }
    }

    private void getfromUIg1(Producer p) {
// ΤΟ ΑΦΜ ΔΕΝ ΑΛΛΑΖΕΙ ΕΙΝΑΙ ΜΑΡΜΑΡΙΝΟ
// p.setProducerAfm(producer_afm.getText());
// εδω για καποιον περιεργο λογο το producer_aeer_id ειναι 
// δηλωμενο ως bigint(20) και το κανει bigint το entity
// απο την αλλη στον πινακα του maae το αντιστοιχο πεδιο 
// ειναι παλι bigint(20) αλλα ο wizard το δημιουργει ως long
// ισως γιατι εχει δηλωμενο το autoincrement?
        p.setProducerSurname(producer_surname.getText());
        p.setProducerFirstName(producer_first_name.getText());
        p.setProducerFatherName(producer_father_name.getText());
        p.setProducerBirthdate(producer_birthdate.getValue());
//   	Set<String> selection = ((ListModelList)country.getModel()).getSelection();
//      if(!selection.isEmpty()){
//		user.setCountry(selection.iterator().next());
//	}else{
//		user.setCountry(null);
//	}
//     αυτος ειναι ο τροπος που το κανουν στο ZK essentials
        Set<Sex> sex = ((ListModelList) producer_sex_id.getModel()).getSelection();
// δεν ξερω για ποιο λογο ακριβως αλλα τα listbox δεν εχουν constraints
// αρα πρεπει να το κανεις manual !!
// δηλαδη αμα δεν εχει τιμη πεταω ενα wrong value exception
        if (!sex.isEmpty()) { // εδω τσεκαρει να δει αν υπαρχει επιλογη
            Sex pSex = sex.iterator().next();
            p.setProducerSexId(pSex);
        } else {
            throw new WrongValueException(producer_sex_id,
                    rb.getString(CaptionsEnum.SELECT_SEX.toString()));
        }

        Set<AdtType> adtTypes = ((ListModelList) producer_adtType_id.getModel()).getSelection();
        if (!adtTypes.isEmpty()) {
            AdtType adtType = adtTypes.iterator().next();
            p.setProducerAdtTypeId(adtType);
        } else {
            throw new WrongValueException(producer_adtType_id,
                    rb.getString(CaptionsEnum.SELECT_GENERIC.toString()));

        }

// και ετσι το εκανα εγω.
//      ListModel<Sex> s = producer_sex_id.getListModel();
//      εδω τραβαω την επιλογη, αν δεν υπαρχει selected item 
//      το index θα ειναι -1 και θα μου το πεταξει σε msgbox !!!!
//      Sex psex = s.getElementAt(producer_sex_id.getSelectedIndex());
//      p.setProducerSexId(psex);
//      ListModel<AdtType> a = producer_adtType_id.getListModel();
//      AdtType at = a.getElementAt(producer_adtType_id.getSelectedIndex());
//      p.setProducerAdtTypeId(at);
//      Set<AdtType> ats = ((ListModelList) producer_adtType_id.getModel()).getSelection();
//      if (!ats.isEmpty()) { // εδω τσεκαρει να δει αν υπαρχει επιλογη
//            p.setProducerAdtTypeId(ats.iterator().next());
//        } else {
//           throw new WrongValueException(producer_adtType_id,
//                    rb.getString(CaptionsEnum.SELECT_ADT_TYPE.toString()));
//        }
        p.setProducerAdt(producer_adt.getText());
        p.setProducerAdtIssueDate(producer_adt_issue_date.getValue());
        p.setProducerAdtIssueDepartment(producer_adt_issue_department.getValue());
        p.setProducerPhone(producer_phone.getValue().toString());

        //Messagebox.show(producer_mobile_phone.gette
        p.setProducerMobilePhone(producer_mobile_phone.getRawText());
        p.setProducerFax(producer_fax.getValue());
        p.setProducerEmail(producer_email.getValue());

    }

    private void getfromUIg2(Producer p) {
        Set<Region> rs = ((ListModelList) producer_region_id.getModel()).getSelection();
        if (rs.isEmpty()) {
            throw new WrongValueException(producer_region_id,
                    rb.getString(CaptionsEnum.SELECT_REGION.toString()));
        }

        Set<Prefecture> ps = ((ListModelList) producer_prefecture_id.getModel()).getSelection();
        if (ps.isEmpty()) {
            throw new WrongValueException(producer_prefecture_id,
                    rb.getString(CaptionsEnum.SELECT_PREFECTURE.toString()));
        }

        Set<Municipality> ms = ((ListModelList) producer_municipality_id.getModel()).getSelection();
        if (!ms.isEmpty()) { // εδω τσεκαρει να δει αν υπαρχει επιλογη
            p.setProducerMunicipalityId(ms.iterator().next());

        } else {
            throw new WrongValueException(producer_municipality_id,
                    rb.getString(CaptionsEnum.SELECT_MUNICIPALITY.toString()));
        }

//        ListModel<Municipality> m = producer_municipality_id.getListModel();
//        Municipality municipality = m.getElementAt(producer_municipality_id.getSelectedIndex());
//        p.setProducerMunicipalityId(municipality);
        p.setProducerAddressStreet(producer_address_street.getValue());
        p.setProducerAddressNumber(producer_address_number.getValue());
        p.setProducerAddressZip(producer_address_zip.getRawText());

    }

    private void getfromUIg3(Producer p) {
        Set<Region> rs = ((ListModelList) producer_rural_region_id.getModel()).getSelection();
        if (rs.isEmpty()) {
            throw new WrongValueException(producer_rural_region_id,
                    rb.getString(CaptionsEnum.SELECT_REGION.toString()));
        }

        Set<Prefecture> ps = ((ListModelList) producer_rural_prefecture_id.getModel()).getSelection();
        if (ps.isEmpty()) {
            throw new WrongValueException(producer_rural_prefecture_id,
                    rb.getString(CaptionsEnum.SELECT_PREFECTURE.toString()));
        }

        Set<Municipality> ms = ((ListModelList) producer_rural_municipality_id.getModel()).getSelection();
        if (!ms.isEmpty()) { // εδω τσεκαρει να δει αν υπαρχει επιλογη
            p.setProducerRuralMunicipalityId(ms.iterator().next());
        } else {
            throw new WrongValueException(producer_rural_municipality_id,
                    rb.getString(CaptionsEnum.SELECT_MUNICIPALITY.toString()));
        }

        p.setProducerRuralAddressStreet(producer_rural_address_street.getValue());
        p.setProducerRuralAddressNumber(producer_rural_address_number.getValue());
        p.setProducerRuralAddressZip(producer_rural_address_zip.getValue());

    }

    private void getfromUIg4(Producer p) {

        Set<UnitLocationType> locationTypes
                = ((ListModelList) unitLocation.getModel()).getSelection();

        if (!locationTypes.isEmpty()) {
            p.setProducerUnitLocationTypeId(locationTypes.iterator().next());
        } else {
            throw new WrongValueException(unitLocation,
                    rb.getString(CaptionsEnum.SELECT_UNIT.toString()));
        }

        Set<Daok> ds = ((ListModelList) producer_daok_cd.getModel()).getSelection();
        if (!ds.isEmpty()) { // εδω τσεκαρει να δει αν υπαρχει επιλογη
            p.setProducerDaokCd(ds.iterator().next());
        } else {
            throw new WrongValueException(producer_daok_cd,
                    rb.getString(CaptionsEnum.SELECT_DAOK.toString()));
        }

    }

    private void updateUIg1(Producer p) {
        g1.setVisible(true); // μην τυχον και το εχουμε ξεχασει...

        setTextboxValue(producer_afm, p.getProducerAfm());
        setTextboxValue(producer_surname, p.getProducerSurname());

        setTextboxValue(producer_first_name, p.getProducerFirstName());

        setTextboxValue(producer_father_name, p.getProducerFatherName());

        setDateboxValue(producer_birthdate, p.getProducerBirthdate());

        // εδω περναω κατευθειαν το id στο index γιατι συμπηπτουν
        // δεν ειναι σωστο ομως... αμα αλλαξει σειρα το id με το index 
        // θα γινει μπαχαλο
        //  producer_sex_id.setSelectedIndex(p.getProducerSexId().getSexId());
        // και για αυτο εφτιαξα το παρακατω που ψαχνει και "κουμπωνει" τα ids
        // βεβαια εξακολουθει απαραιτητη προυποθεση τα κλειδια μου να συμφωνουν με
//        ListModel<Sex> s = producer_sex_id.getListModel();
//        for (int j = 0; j < s.getSize(); j++) {
//            Sex psex = s.getElementAt(j);
//            if (psex.getSexId() != p.getProducerSexId().getSexId()) {
//            } else {
//                producer_sex_id.setSelectedIndex(j);
//                break;
//            }
//        }
        if (p.getProducerSexId() != null) {
            ((ListModelList) producer_sex_id.getModel())
                    .addToSelection(p.getProducerSexId());
        }

        if (p.getProducerAdtTypeId() != null) {
            ((ListModelList) producer_adtType_id.getModel())
                    .addToSelection(p.getProducerAdtTypeId());
        }

//        ListModel<AdtType> a = producer_adtType_id.getListModel();
//        for (int i = 0; i < a.getSize(); i++) {
//            AdtType padt = a.getElementAt(i);
//            if (padt.getAdtTypeId() != p.getProducerAdtTypeId().getAdtTypeId()) {
//            } else {
//                producer_adtType_id.setSelectedIndex(i);
//                break;
//            }
//        }
//        ListModel<Sex> s = producer_sex_id.getListModel();
//        for (int i = 0; i < s.getSize(); i++) {
//            Sex psex = s.getElementAt(i);
//            if (psex.getSexId() != p.getProducerSexId().getSexId()) {
//            } else {
//                producer_sex_id.setSelectedIndex(i);
//                break;
//            }
//        }
//        
//        String s = p.getProducerPhone();
//        
//        if (!s.isEmpty()) {
//           producer_phone.setValue(s);
//       }
        setTextboxValue(producer_adt, p.getProducerAdt());

        setDateboxValue(producer_adt_issue_date, p.getProducerAdtIssueDate());

        setTextboxValue(producer_adt_issue_department,
                p.getProducerAdtIssueDepartment());

        setTextboxValue(producer_phone, p.getProducerPhone());

        setTextboxValue(producer_mobile_phone, p.getProducerMobilePhone());
        setTextboxValue(producer_fax, p.getProducerFax());
        setTextboxValue(producer_email, p.getProducerEmail());

//String dep = p.getProducerAdtIssueDepartment();
        //if (!dep.equals("")) {
        //    producer_adt_issue_department.setValue(p.getProducerAdtIssueDepartment());
        // }
        //producer_phone.setValue(p.getProducerPhone());
        //producer_mobile_phone.setValue(p.getProducerMobilePhone());
        //producer_email.setValue(p.getProducerEmail());
    }

    private void updateUIg2(Producer p) {
//       ((ListModelList) producer_adtType_id.getModel())
//                .addToSelection(p.getProducerAdtTypeId());
//        
        Municipality municipality = p.getProducerMunicipalityId();

        if (municipality != null) {

            Region region = p.getProducerMunicipalityId()
                    .getMunicipalityPrefectureId()
                    .getPrefectureRegionId();

            ((ListModelList) producer_region_id.getModel())
                    .addToSelection(region);

            regionSelect();

            Prefecture prefecture = p.getProducerMunicipalityId()
                    .getMunicipalityPrefectureId();

            ((ListModelList) producer_prefecture_id.getModel())
                    .addToSelection(prefecture);

            prefectureSelect();

            ((ListModelList) producer_municipality_id.getModel())
                    .addToSelection(p.getProducerMunicipalityId());

        }

        setTextboxValue(producer_address_street, p.getProducerAddressStreet());
        setTextboxValue(producer_address_number, p.getProducerAddressNumber());
        producer_address_zip.setRawValue(p.getProducerAddressZip());

    }

    private void updateUIg3(Producer p) {

        Municipality municipality = p.getProducerRuralMunicipalityId();

        if (municipality != null) {
            Region region = p.getProducerRuralMunicipalityId()
                    .getMunicipalityPrefectureId()
                    .getPrefectureRegionId();

            ((ListModelList) producer_rural_region_id.getModel())
                    .addToSelection(region);

            ruralRegionSelect();

            Prefecture prefecture = p.getProducerRuralMunicipalityId()
                    .getMunicipalityPrefectureId();

            ((ListModelList) producer_rural_prefecture_id.getModel())
                    .addToSelection(prefecture);

            ruralPrefectureSelect();

            ((ListModelList) producer_rural_municipality_id.getModel())
                    .addToSelection(p.getProducerMunicipalityId());

            //       setTextboxValue(producer_rural_address_street, 
            //             p.getProducerRuralAddressStreet());
//        producer_rural_address_street.setValue(p.getProducerRuralAddressStreet());
        }

        setTextboxValue(producer_rural_address_street, p.getProducerRuralAddressStreet());
        setTextboxValue(producer_rural_address_number, p.getProducerRuralAddressNumber());
        setTextboxValue(producer_rural_address_zip, p.getProducerRuralAddressZip());

    }

    private void updateUIg4(Producer p) {

        // ΦΑΝΤΑΣΤΙΚΟ BUG !!! περγαγα null στο addToSelection και αυτο το εβαζε
        // 
        if (p.getProducerUnitLocationTypeId() != null) {
            ((ListModelList) unitLocation.getModel())
                    .addToSelection(p.getProducerUnitLocationTypeId());
        }

        if (p.getProducerDaokCd() != null) {
            ((ListModelList) producer_daok_cd.getModel())
                    .addToSelection(p.getProducerDaokCd());
        }
    }

    private void updateUIg5(Producer p) {

        // φτιανουμε μια λιστα για τον producer αν δεν υπαρχει
        if (producerToSave.getProductionList() == null) {
            ArrayList<Production> productions = new ArrayList<Production>();
            producerToSave.setProductionList(productions);
        }

        // και την βαζουμε για listmodel του production Listbox
        ListModelList<Production> listModelList;

        listModelList = new ListModelList<Production>(producerToSave.getProductionList());

        production.setModel(listModelList);

    }

    public void saveProducer() {

        // BAZOYME TON ΠΑΡΑΓΩΓΟ
        // δουλευει αυτο αλλα δεν θελω να κανει εγγραφες ακομα 
        if (new_producer == true) {
            //     Messagebox.show("Η εγγραφή μάλλον δημιουργήθηκε και καταχωρηθηκε !!!!");
            producerJpaController.create(producerToSave);
            new_producer = false;
        } else {
            //     Messagebox.show("Η εγγραφή μάλλον ενημερωθηκε !!!!");
            try {
                producerJpaController.edit(producerToSave);
            } catch (NonexistentEntityException ex) {
                Logger.getLogger(ProducerBL1.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(ProducerBL1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void setProducerSubmitted(Producer producer) throws NonexistentEntityException, Exception {

        producer.setProducerSubmittedAppliation(true);
        producer.setProducerSubmittedApplicationDate(new Date());
        producer.setProducerConfirmed(false);
        
        String prid = String.format("%06d", producer.getProducerId());
        
        String nomos = producer.getProducerDaokCd().getDaokCd().substring(0,2);
        
        producer.setProducerRegisterCd("GR" + nomos + prid);
        producerJpaController.edit(producer);

    }

    @Listen("onClick = #producer_submit")
    public void onSubmit() {

        EventListener<ClickEvent> el = new EventListener<ClickEvent>() {

            public void onEvent(Messagebox.ClickEvent e) throws Exception {
                switch (e.getButton()) {
                    case YES: //OK is clicked
                        setProducerSubmitted(producerToSave);
                        g5.setVisible(false);
                        g6.setVisible(true);
                    case NO: //Cancel is clicked
                    default: //if the Close button is clicked, e.getButton() returns null
                }
            }
        ;

        };
            
        Messagebox.Button[] buttons = {Messagebox.Button.YES, Messagebox.Button.NO};

        if (!producerToSave.getProductionList().isEmpty()) {
            Messagebox.show("Να γινει οριστική υποβολή ;",
                    "Οριστική Υποβολη", buttons,
                    Messagebox.QUESTION, el);
        } else {
            Messagebox.show("Δεν εχετε υποβάλει στοιχεία παραγωγής, παρακαλώ καταγραψτε στοιχεια"
                    + "παραγωγης σας και πατηστε ΠΡΟΣΘΗΚΗ");
        }

        // @TODO : BUG δεν ελεγχει για null δαοκ ??
    }

    @Listen("onBlur = #production_farm_osde")
    public void onProductionFarmOsdeBlur() {
        String osde = production_farm_osde.getValue();
        if (osde.equals("")) {
            production_farm_osde.setValue("ΛΑΧΑΝΟΚΗΠΟΣ");
        }

    }

    @Listen("onBlur = #production_farm_area")
    public void onProductionFarmAreaBlur() {

        String osde = production_farm_osde.getValue();

        if (osde.equals("")) {
            production_farm_osde.setValue("ΛΑΧΑΝΟΚΗΠΟΣ");
        }

        osde = production_farm_osde.getValue();
        Double area = production_farm_area.getValue();

        if (osde.equals("ΛΑΧΑΝΟΚΗΠΟΣ") && (area > 1)) {
            throw new WrongValueException(production_farm_area, "Μεγαλη εκταση για οικιακο λαχανόκηπο !!! Πρεπει να ειναι λιγοτερη απο 1 !");

        }

    }

    @Listen("onClick = #printApplication")
    public void onPrintApplicationClick() throws SQLException, JRException {

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            System.out.println("Error: unable to load driver class!");
            System.exit(1);
        }

        String URL = "jdbc:mysql://localhost:3306/kimo";
        String USER = "kimo";
        String PASS = "kimo";
        Connection conn = DriverManager.getConnection(URL, USER, PASS);

        String realPath = Executions.getCurrent().getDesktop().
                getWebApp().getRealPath("/");

        String reportFile = realPath + "/reports/ProducerApplication.jasper";

        Map parameters = new HashMap();

        String producerid = producerToSave.getProducerId().toString();

        parameters.put("producerID", producerid);

        JasperPrint fillReport = JasperFillManager.fillReport(reportFile, parameters, conn);

        String filename;

        filename = producerToSave.getProducerAfm() + "App.pdf";

        AMedia media = new AMedia(filename, null, null,
                JasperExportManager.exportReportToPdf(fillReport));

        Filedownload.save(media);

    }

}
